package com.xxx.common.redis.configure;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {

    @Value("${spring.data.redis.host}")
    private String redisHost;

    @Value("${spring.data.redis.port}")
    private String redisPort;

    @Value("${spring.data.redis.database}")
    private Integer redisDatabase;

    @Value("${spring.data.redis.password}")
    private String redisPassword;

    @Value("${spring.data.redis.timeout}")
    private Integer redisTimeout;

    @Value("${spring.data.redis.lettuce.pool.max-active:64}")
    private int poolMaxActive;

    @Value("${spring.data.redis.lettuce.pool.min-idle:24}")
    private int poolMinIdle;

    @Value("${spring.data.redis.lettuce.pool.max-wait:10000}")
    private int poolMaxWait;

    @Bean(name = "redisson", destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        Config config = new Config();

        redisHost = redisHost.startsWith("redis://") ? redisHost : "redis://" + redisHost;

        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress(redisHost + ":" + redisPort)
                .setDatabase(redisDatabase)
                .setTimeout(redisTimeout)
                // 使用 Lettuce 的连接池配置
                .setConnectionPoolSize(poolMaxActive)          // max-active
                .setConnectionMinimumIdleSize(poolMinIdle)     // min-idle
                .setIdleConnectionTimeout(poolMaxWait);        // max-wait

        if (StringUtils.isNotBlank(redisPassword)) {
            serverConfig.setPassword(redisPassword);
        }

        return Redisson.create(config);
    }
}